<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">
      <el-form-item label="检索" prop="search">
        <el-input v-model="queryParams.search" placeholder="请输入检索条件" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['carbon:product:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['carbon:product:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['carbon:product:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" label="编号" />
      <el-table-column label="生产单位" prop="productName" />
      <el-table-column label="图片" align="center" prop="img">
        <template slot-scope="scope">
          <el-image :src="scope.row.img" fit="cover" style=" width:50; height:50;">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" width="120">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.createBy != null">
            {{ scope.row.createBy }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无创建人
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.createTime != null">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无日期
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy" width="120">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.updateBy != null">
            {{ scope.row.updateBy }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无修改人
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" align="center" prop="updateTime" width="100">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.updateTime != null">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无日期
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['carbon:product:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['carbon:product:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改生产单位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生产单位" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入生产单位" />
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload class="upload-demo" v-model="form.img" action="/dev-api/wms/provider/upload"
            :on-success="handleSuccess" :file-list="fileList" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="'1'">隐藏</el-radio>
            <el-radio :label="'0'" checked>显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" @change="handleChange" :min="0" :max="10" label="请选择排序"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-divider content-position="center">生产批号信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddBatch">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteBatch">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="batchList" :row-class-name="rowBatchIndex" @selection-change="handleBatchSelectionChange"
          ref="batch">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" width="50" label="编号" />
          <el-table-column label="生产批号" prop="batchId" width="150" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchId" placeholder="请输入生产批号" :disabled="scope.row.id != null" />
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="100" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                @change="handleStatusChange1(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort" width="150" align="center">
            <template slot-scope="scope">
              <el-input-number size="small" v-model="scope.row.sort" :min="0" :max="10" label="请选择排序"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { changeProductStatus, listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/wms/product";
import { changeBatchStatus, delBatch } from "@/api/wms/batch";
export default {
  name: "Product",
  data () {
    return {
      // 文件列表
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBatch: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产单位表格数据
      productList: [],
      // 生产批号表格数据
      batchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        search: null
      },
      // 表单参数
      form: {
        status: '0',
        sort: '0'
      },
      // 表单校验
      rules: {
      }
    };
  },
  created () {
    this.getList();
  },
  methods: {
    handleChange (value) {
      this.form.sort = value
    },
    // 上传成功 回调函数
    handleSuccess (response, file, fileList) {
      console.log(response);
      var data = {
        name: response.name,
        url: response.file
      }
      this.fileList.push(data)
      this.form.img = response.file
    },
    // 修改生产批号状态
    handleStatusChange1 (row) {
      if (row.id != null) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + row.batchId + '"吗？').then(function () {
          return changeBatchStatus(row.id, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
          this.getList()
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
      }

    },
    // 修改生产单位状态
    handleStatusChange (row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + row.productName + '"吗？').then(function () {
        return changeProductStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList()
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 查询生产单位列表 */
    getList () {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.fileList = []
      this.form = {
        status: '0',
        sort: '0'
      };
      this.batchList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10,
        search: null
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加生产单位";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        if (response.data.img != null) {
          this.fileList.push({
            name: response.data.img,
            url: response.data.img
          })
        }

        if (response.data.batchList != null) {
          this.batchList = response.data.batchList;
        }
        this.open = true;
        this.title = "修改生产单位";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.batchList = this.batchList;
          addProduct(this.form).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除生产单位编号为"' + ids + '"的数据项？').then(function () {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 生产批号序号 */
    rowBatchIndex ({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 生产批号添加按钮操作 */
    handleAddBatch () {
      let obj = {};
      obj.batchId = "";
      obj.status = "0";
      obj.remark = "";
      obj.sort = "1";
      this.batchList.push(obj);
    },
    /** 生产批号删除按钮操作 */
    handleDeleteBatch () {
      if (this.checkedBatch.length == 0) {
        this.$modal.msgError("请先选择要删除的生产批号数据");
      }
      else {
        this.checkedBatch.forEach(item => {
          if (this.batchList[item - 1].id != null) {
            delBatch(this.batchList[item - 1].id).then(res => {

            })
          }
        })
        const batchList = this.batchList;
        const checkedBatch = this.checkedBatch;
        this.batchList = batchList.filter(function (item) {
          return checkedBatch.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleBatchSelectionChange (selection) {
      this.checkedBatch = selection.map(item => item.index)
    },

  }
};
</script>
<style lang="scss" scoped>
.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;

  ::v-deep .el-image__inner {
    transition: all 0.3s;
    cursor: pointer;

    &:hover {
      transform: scale(1.2);
    }
  }

  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 30px;
  }
}
</style>
